from django.shortcuts import render, HttpResponseRedirect, redirect
import datetime
from .models import *
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.core import serializers
from django.db.models import Sum, Count
import json
import random
from .models import warehouse as Warehouse
from django.contrib import messages
from django.http import Http404
from django.http import HttpResponseRedirect
from .routine_task import *
from django.db.models import Q


# Create your views here.


# 通知生成
def create_notification(content, note_type, receiver_id, serious="1", url="", creator_id=1):
    """
    :param content:  通知内容
    :param note_type:  {1: 商品过期, 2: 操作通知} type: int or str
    :param receiver_id:  收到通知的用户id  type: int
    :param serious:  默认1
    :param url:  默认空
    :param creator_id:  默认1->admin
    """
    note_info.objects.create(n_type=str(note_type), n_content=content, n_url=url, n_serious=str(serious),
                             n_creator_id=creator_id, n_receiver_id=receiver_id)


# 主页
@login_required
def index(req):
    # TODO 实现主页相关内容显示
    user = User.objects.get(id=int(req.session["_auth_user_id"]))
    demand_num = Demand.objects.filter(isSolved=False).count()
    sale_num = SaleOrder.objects.filter(status="未发货").count()
    return render(req, "index.html",
                  {"username": user.username, "name": user.u_name,
                   "job": user.u_occupation, "number": "%04d" % user.id,
                   "phone": user.u_phone, "warehouse": user.u_work_place,
                   "cap": {'rate': 50, 'vol': 300, 'total': 600},
                   'sales': sale_num, "demand": demand_num})


# 登录
def login(req):
    if req.method == 'GET':
        if req.GET.get("logout"):
            auth.logout(req)

            return render(req, "page-login.html", {})

        if req.user.is_authenticated:
            return HttpResponseRedirect('../')

        return render(req, "page-login.html", {})

    else:
        username = req.POST.get("username")
        password = req.POST.get("password")
        remember = req.POST.get("remember")
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            auth.login(req, user)
            if remember:
                req.session.set_expiry(60 * 60 * 24 * 7)  # 有效期7天
            else:
                req.session.set_expiry(60 * 60 * 3)
            next_url = req.GET.get('next') or '../'
            return HttpResponseRedirect(next_url)
        else:
            return render(req, "page-login.html", {"result": "fail"})


# 用户信息
@login_required
def profile(req):
    # TODO 实现个人信息界面
    username = req.GET.get("username")
    name = "Test"
    job = "超级管理员"
    number = "0001"
    phone = "13000000000"
    return render(req, "", {})


# 查看库存
@login_required
def warehouse(req):
    warehouse_id = User.objects.get(id=int(req.session["_auth_user_id"])).u_warehouse_id
    batch_storage = storage.objects.filter(warehouse_id=warehouse_id)
    total_storage = storage.objects.filter(warehouse_id=warehouse_id).values("p_ID_id", "p_name", "p_type", "p_package",
                                                                             "p_ID__p_expiration",
                                                                             "p_ID__p_weight").annotate(
        sum=Sum("s_number"))

    # 这里用不了models写的type_str属性只能遍历改一遍了
    type_dict = {"1": "巴氏消毒奶", "2": "脱脂奶", "3": "常温奶", "4": "高钙牛奶", "5": "生鲜牛奶", "6": "灭菌牛奶",
                 "7": "无抗奶", "8": "调味奶"}
    for item in total_storage:
        item["p_type"] = type_dict[item["p_type"]]
    return render(req, "warehouse.html",
                  {"warehouse_id": warehouse_id, "batch_storage": batch_storage, "total_storage": total_storage,
                   "temperature": 0})


# 查看通知
@login_required
def notification(req):
    # TODO 确定通知种类
    if req.is_ajax():
        if req.GET.get("type") == "display":
            note_list = note_info.objects.filter(n_receiver_id=int(req.session["_auth_user_id"])).order_by("-n_time")
            count = note_list.count()
            if count > 4:  # 4条之后不显示
                note_list = note_list[:4]
            note_list = serializers.serialize("json", note_list)
            return JsonResponse({"count": count, "note_list": note_list})
        elif req.GET.get("type") == "delete":
            note_info.objects.get(id=int(req.GET.get("id"))).delete()

    note_list = note_info.objects.filter(n_receiver_id=int(req.session["_auth_user_id"])).order_by("-n_time")
    return render(req, "notification.html", {"note_list": note_list})


# 查看过期产品
@login_required
def expired(req):
    # TODO 过期删除后修改货架存储信息，仓库流水
    if req.is_ajax():
        handle_type = req.POST.get("type")
        data = req.POST.get("data")
        data = json.loads(data)
        for item in data:
            storage.objects.get(p_ID_id=item[0], s_order_ID=item[-1]).delete()

        return JsonResponse({"result": "success"})

    warehouse_id = User.objects.get(id=int(req.session["_auth_user_id"])).u_warehouse_id
    product_list = storage.objects.filter(expired=True, warehouse_id=warehouse_id)
    return render(req, "expired.html", {"warehouse_id": warehouse_id, "product_list": product_list})


# 增加商品
@login_required
def add_goods(req):
    user = User.objects.get(id=int(req.session["_auth_user_id"]))

    # 货架匹配
    def find_avai_position(warehouse, p_id, p_number):
        print(warehouse.warehouse_id)
        shelves = shelf.objects.filter(is_available=True, warehouse=warehouse).all()
        for i in shelves:
            print(p_number)
            print(i.volume)
            print(i.volume_used)
            if int(p_number) < i.volume - i.volume_used:
                i.volume_used += int(p_number)
                i.save()
                return i
        return None

    # TODO 实现商品入库，确认送往位置，修改货架存储信息以及仓库流水
    if req.method == "POST":
        if req.GET.get("type") == "goods":
            # 新增商品
            goods_product = req.POST.get("goods_product")
            goods_type = req.POST.get("goods_type")
            # 商品id随便编一下吧
            goods_id = "%s0%s1%02d" % (
                goods_product[1:], goods_type,
                product.objects.filter(p_product=goods_product, p_type=goods_type).count())

            product.objects.create(p_id=goods_id, p_name=req.POST.get("goods_name"), p_type=goods_type,
                                   p_package=req.POST.get("goods_pkg_type"), p_price=float(req.POST.get("goods_price")),
                                   p_expiration=int(req.POST.get("goods_expiration")),
                                   p_weight=int(req.POST.get("goods_weight")),
                                   p_cold=True if req.POST.get("goods_cold") == "yes" else False,
                                   p_product=goods_product, p_height=int(req.POST.get("goods_height")),
                                   p_width=int(req.POST.get("goods_width")), p_length=int(req.POST.get("goods_length")))

            return render(req, "add_goods.html", {"goods_id": goods_id})

        elif req.GET.get("type") == "warehouse":
            # 商品入库
            position_list = []
            s_order_id = req.POST.get('order_number')
            print(s_order_id)
            item_number = int(req.POST.get('item_number'))
            # print(req.POST)
            purchase = PurchaseOrder.objects.filter(number=s_order_id).first()
            if not purchase:
                messages.add_message(req, messages.INFO, "订单号{}错误，请检查并重新输入".format(s_order_id))
                return render(req, "add_goods.html", {})
            for i in range(item_number):
                p_id = req.POST.get('goods_id_' + str(i))
                # p_name = req.POST.get('goods_name')
                p = product.objects.filter(p_ID=p_id).first()
                if p is None:
                    messages.add_message(req, messages.INFO, "商品ID{}错误，请检查并重新输入".format(eval(p_id)))
                    return render(req, "add_goods.html", {})
                p_name = p.p_name
                p_type = p.p_type
                p_package = p.p_package
                p_number = int(req.POST.get('goods_number_' + str(i)))
                p_date = datetime.datetime.strptime(req.POST.get('production_date_' + str(i)), "%Y-%m-%d")
                # print(p_date)
                # p_type = req.POST.get('goods_type')
                # p_place = req.POST.get('production_place')
                # 简单匹配规则找到货架位置
                position = find_avai_position(user.u_warehouse, p_id, p_number)
                if not position:
                    # print(position)
                    position = shelf.objects.filter(s_id="0003").first()
                    position_list.append((p_name, {"s_x": 0, "s_y": 0, "s_id": "暂无"}))
                else:
                    position_list.append((p_name, position))
                expired_date = p_date + datetime.timedelta(days=p.p_expiration)
                s = storage(s_order_ID=s_order_id,
                            p_ID=p,
                            p_name=p_name,
                            p_type=p_type,
                            p_package=p_package,
                            s_number=p_number,
                            product_date=p_date,
                            expired_date=expired_date,
                            expired=False,
                            warehouse=user.u_warehouse,
                            shelf=position)
                s.save()
                f_id = s_order_id[:10] + "00" + datetime.datetime.now().strftime("%S") + str(i)
                flow = Flow(f_id=f_id,
                            p_ID=p,
                            p_number=p_number,
                            f_type="0",
                            memo="",
                            f_warehouse=user.u_warehouse)
                flow.save()
                accept = Accept(s_order_ID=s_order_id,
                                product_date=p_date,
                                number=p_number,
                                p_ID=p)
                accept.save()
            purchase.isReceived = True
            purchase.save()
            return render(req, "add_goods.html", {"position": position_list})
    goods_supplier = supplier.objects.values_list("sup_id", "sup_name")
    order_number = PurchaseOrder.objects.filter(warehouse=user.u_warehouse, isReceived=False,
                                                isClosed=False).values("number")

    return render(req, "add_goods.html", {"goods_supplier": goods_supplier, "order_number": order_number})


# 查看所有仓库
@login_required
def view_warehouse(req):
    # warehouse_list = [{"warehouse_id": 1, "w_manager_id": 2, "w_address": 3},
    #                   {"warehouse_id": 1, "w_manager_id": 2, "w_address": 3},
    #                   {"warehouse_id": 1, "w_manager_id": 2, "w_address": 3},
    #                   {"warehouse_id": 1, "w_manager_id": 2, "w_address": 3}]
    warehouse_list = Warehouse.objects.all()
    return render(req, "view_warehouse.html", {"warehouse_list": warehouse_list})


# 注册
def register(req):
    if req.is_ajax():
        if req.method == 'GET':
            if len(User.objects.filter(username=req.GET.get("username"))) == 1:
                return JsonResponse({'result': '1'})
            else:
                return JsonResponse({'result': '0'})
    if req.method == "POST":
        username = req.POST.get("username")
        password = req.POST.get("password")
        name = req.POST.get("name")
        occupation = req.POST.get("occupation")
        address = req.POST.get("address")
        work_place = req.POST.get("work_place")
        phone = req.POST.get("phone")
        User.objects.create_user(username=username, password=password, u_name=name, u_occupation=occupation,
                                 u_address=address, u_work_place=work_place, u_phone=phone)

        if User.objects.filter(username=username):
            # 检验创建成功后顺便登录
            user = auth.authenticate(username=username, password=password)
            auth.login(req, user)
            return HttpResponseRedirect('../')

    return render(req, "register.html", {})


# 车辆监控
@login_required
def real_time_location(req):
    temp_list = Warehouse.objects.all()
    warehouse_list = []
    for i in temp_list:
        warehouse_list.append([i.w_longtitude, i.w_latitude, i.w_address, i.warehouse_id, i.w_n_shelf])
    return render(req, "real_time_location.html", {'warehouse_list': json.dumps(warehouse_list)})


# 获取实时数据
def get_data(req):
    from .routine_task import vechile_data
    return JsonResponse({"data": vechile_data}, content_type="application/json")


# 销售订单详情
@login_required
def sales_order_info(req, id):
    order = SaleOrder.objects.filter(o_id=id).first()
    items = order.saleinfo_set.all()
    sufficient = []
    for i in items:
        storages = storage.objects.filter(p_ID=i.p_id).all()
        number = sum([i.s_number for i in storages])
        sufficient.append(1 if number >= i.number else 0)
    print(sufficient)
    if req.method == "POST":
        if sum(sufficient) != len(sufficient):
            messages.add_message(req, messages.ERROR, "货物不足，无法发货")
            return HttpResponseRedirect('/sales_order')
        else:
            # 后端关键任务2：根据订单生成运输任务，并执行货物的调配,同时通知库存管理人员
            generate_drive_task(order)
            messages.add_message(req, messages.SUCCESS, "已生成发货任务")
            order.status = "已发货"
            order.save()
            return HttpResponseRedirect('/sales_order')
    return render(req, 'sales_order_info.html',
                  {'shop_list': [{"item": i, "sufficient": j} for i, j in zip(items, sufficient)], 'order': order})


# 销售订单列表
@login_required
def sales_order(req):
    d = SaleOrder.objects.all()
    return render(req, 'sales_order.html', {'order_list': d})


# 配送任务信息
@login_required
def invoice_info(req):
    # invoice_d = [{"invoice_id": 1}, {"invoice_id": 2}]
    invoice_d = invoice.objects.all()
    return render(req, 'invoice_info.html', {'invoice_list': invoice_d})


# 维修车辆管理
@login_required
def service_info(req):
    # wait_to_service = trucks.objects.filter(~Q(truck_id__in=avai_trucks.objects.values('truck_id'))).all()
    # for w in wait_to_service:
    #     if random.randint(1,100) > 70:
    #         cur_service = service_trucks(truck_id=w.truck_id,truck_pattern=w.truck_pattern,service_status="正在维修中",service_det="无")
    #         cur_service.save()
    #     else:
    #         continue
    service_d = service_trucks.objects.all()
    return render(req, 'service_info.html', {'service_list': service_d})


# 报废车辆信息
@login_required
def scrap_info(req):
    # wait_to_service = trucks.objects.filter(~Q(truck_id__in=avai_trucks.objects.values('truck_id'))).all()
    # for w in wait_to_service:
    #     if random.randint(1,100) > 70:
    #         cur_scrap = scrapped_trucks(truck_id=w.truck_id,truck_pattern=w.truck_pattern,scrapped_dest="未处理",scrapped_det="无")
    #         cur_scrap.save()
    #     else:
    #         continue
    scrap_d = scrapped_trucks.objects.filter(~Q(scrapped_dest="未处理")).all()
    return render(req, 'scrap_info.html', {'scrap_list': scrap_d})


# 异常处理
@login_required
def exception_handle_info(req):
    #采用随机数机制生成异常
    # if abnormal.objects.all():
    # cur = abnormal.objects.all().order_by('-abnormal_id').first()
    #     # abnormal_id = cur.abnormal_id if cur else "0"
    #     # id = int(abnormal_id)
    #     # reason = ["设备问题","道路异常拥堵","交通事故"]
    #     # if random.randint(1,10)>7:
    #     #     id+=1
    #     #     t_ab = abnormal(abnormal_id=str(id).zfill(4),abnormal_ispro=0,abnormal_reas=reason[random.randint(0,2)],abnormal_time=date.today(),schedule_id=schedule.objects.first().schedule_id)
    #     #     t_ab.save()
    exception_handle_d = abnormal.objects.all()
    return render(req, 'exception_handle_info.html', {'exception_handle_d': exception_handle_d})


# 异常处理结果返回
def exception_handle_process(req, id):
    if req.method == "POST":
        messages.add_message(req, messages.SUCCESS, "处理成功")
        abnormal.objects.filter(schedule_id=id).update(abnormal_ispro=1)
        return HttpResponseRedirect("/exception_handle_info")
    return render(req, 'exception_handle_process.html', {"id": id})


# 可用车辆管理
@login_required
def avai_trucks_info(req):
    avai_trucks_d = avai_trucks.objects.all()
    return render(req, 'avai_trucks.html', {'avai_trucks_d': avai_trucks_d})


# 司机信息查看
def driver_info(req, id):
    driver_d = drivers.objects.filter(driver_id=id).first()

    return render(req, 'driver_info.html', {'driver_d': driver_d})


# 车辆信息查看
def truck_status(req, id):
    truck_d = avai_trucks.objects.filter(truck_id=id).first()

    return render(req, 'truck_status.html', {'truck_d': truck_d})


# 车辆资产管理
def truck_asset_manage(req):
    # avai_tru = avai_trucks.objects.all()
    # truck_pattern = ["C11A","C11B","C21A","C21B","C31A","C31B"]
    # count_l = [0,0,0,0,0,0]
    # for a in avai_tru:
    #     count_l[truck_pattern.index(a.truck_pattern)]+=1

    # for i in range(6):
    # #     t_sta = statistics_trucks(pattern_id=str(i).zfill(3),truck_pattern=truck_pattern[i],truck_num=count_l[i],statistics_time=date.today())
    #     t_sta.save()
    count = 0
    asset_info = statistics_trucks.objects.all()
    for truck in asset_info:
        if truck.truck_num < 35:
            count += 1
    service_truck_info = service_trucks.objects.filter(service_status="正在维修中").all()
    scrapped_truck_info = scrapped_trucks.objects.filter(scrapped_dest="未处理").all()
    return render(req, 'truck_asset_manage.html', {'asset_info': asset_info, 'service_truck_info': service_truck_info,
                                                   'scrapped_truck_info': scrapped_truck_info, 'count': count})

# 调度规则
def schedule_manage(req):
    # 审核处理逻辑
    if req.is_ajax():
        if req.GET.get("type") == "pass":
            s_id = req.GET.get("id")
            schedule.objects.filter(schedule_id=s_id).update(schedule_status="正在执行")
            return JsonResponse({"result": "success"})

        elif req.GET.get("type") == "fail":
            s_id = req.GET.get("id")
            shiptask.objects.filter(
                task_id=schedule.objects.filter(schedule_id=s_id).values("task_id")[0]['task_id']).update(is_schedule=0)
            avai_trucks.objects.filter(
                truck_id=schedule.objects.filter(schedule_id=s_id).values("truck_id")[0]['truck_id']).update(
                truck_status="未使用")
            schedule.objects.filter(schedule_id=s_id).delete()
            gen_schedule()
            return JsonResponse({"result": "success"})

    schedule_info_1 = schedule.objects.filter(schedule_status="待审核").all()
    schedule_info_2 = schedule.objects.filter(schedule_status="正在执行").all()
    schedule_info_3 = schedule.objects.filter(schedule_status="执行完毕").all()

    return render(req, 'schedule_manage.html', {'schedule_info_1': schedule_info_1, 'schedule_info_2': schedule_info_2,
                                                'schedule_info_3': schedule_info_3})

# 维修车辆处理
def service_process(req, id):
    if req.method == "POST":
        messages.add_message(req, messages.SUCCESS, "处理成功！")
        det = req.POST["pro_det"]
        service_trucks.objects.filter(truck_id=id).update(service_status="完成维修")
        service_trucks.objects.filter(truck_id=id).update(service_det=det)
        return HttpResponseRedirect("/truck_asset_manage")

    return render(req, 'service_process.html', {'truck_id': id})

# 报废车辆处理
def scrappe_pro(req, id):
    if req.method == "POST":
        messages.add_message(req, messages.SUCCESS, "处理成功！")
        srap_to = req.POST["srap_to"]
        det = req.POST["pro_det"]
        scrapped_trucks.objects.filter(truck_id=id).update(scrapped_dest=srap_to)
        scrapped_trucks.objects.filter(truck_id=id).update(scrapped_det=det)
        return HttpResponseRedirect("/truck_asset_manage")
    return render(req, 'scrappe_pro.html', {'truck_id': id})

# 车辆需求
def truck_demands(req):
    # 假定一提交需求单车辆就会到货
    if req.method == "POST":
        messages.add_message(req, messages.SUCCESS, "提交成功！")
        truck_pat = req.POST["truck_pattern"]
        if truck_pat == '全选':
            real_need = statistics_trucks.objects.filter(truck_num__lt=35).all()
            for n in real_need:
                statistics_trucks.objects.filter(truck_pattern=n.truck_pattern).update(truck_num=35)
        else:
            statistics_trucks.objects.filter(truck_pattern=truck_pat).update(truck_num=35)
        return HttpResponseRedirect("/truck_asset_manage")
    real_need = statistics_trucks.objects.filter(truck_num__lt=35).all()
    for n in real_need:
        n.truck_num = 35 - n.truck_num
    return render(req, 'truck_demands.html', {'real_need': real_need})


# 获得用户身份
def get_occupation(req):
    if req.is_ajax():
        return JsonResponse({"occupation": User.objects.get(id=int(req.session["_auth_user_id"])).u_occupation})


# 生成配送任务
def generate_drive_task(order: SaleOrder):
    # 处理一个仓库
    def ex_warehouse(warehouse, items, order):
        print("操作仓库" + str(warehouse.warehouse_id))
        counter = 0
        while counter < len(items):
            j = items[counter]
            counter += 1
            a = invoice.objects.all().order_by('-invoice_id').first()
            p = j.p_id
            invoice_id = a.invoice_id if a else "0"
            temp_invoice = invoice(invoice_id=str(int(invoice_id) + 1).zfill(6),
                                   invent_loc=i.w_address,
                                   dest_loc=order.customer.c_address,
                                   invoice_time=datetime.datetime.now(),
                                   invoice_prod=p,
                                   invoice_num=j.number)
            number = j.number
            storage_list = warehouse.storage_set.filter(p_ID=j.p_id).order_by('reach_date')
            # 在仓库中逐条对应处理数据
            count = 0
            for k in storage_list:
                if k.s_number > number:
                    ex_storage(k, order.memo, number, count)
                    items.remove(j)
                    count += 1
                    counter -= 1
                    break
                    # 需要逐条生成通知
                else:
                    ex_storage(k, order.memo, k.s_number, count)
                    count += 1
            temp_invoice.save()

    # 处理单条库存
    def ex_storage(storage, memo, number, count):
        print("ex_storage")
        # 1记为出
        f_id = storage.s_order_ID + "01" + datetime.datetime.now().strftime("%S") + str(count)
        p_number = number
        f_type = "1"
        f_time = datetime.datetime.now()
        memo = memo
        f_warehouse_id = i.warehouse_id
        # 仓库流水处理
        f = Flow(f_id=f_id, p_number=p_number, f_type=f_type,
                 f_time=f_time, memo=memo, f_warehouse_id=f_warehouse_id, p_ID=storage.p_ID)
        f.save()
        # 通知生成
        create_notification("请准备出库产品%s,位置%d,%d,数量%d" % (storage.p_name, storage.shelf.s_x, storage.shelf.s_y, p_number),
                            note_type='2',
                            receiver_id=i.user_set.first().id,
                            url="",
                            creator_id=1)
        storage.s_number -= number
        if storage.s_number == 0:
            # 库存处理
            storage.delete()
        else:
            storage.save()
        print("ex_storage over")

    # 先匹配库存，再匹配车辆
    # 库存匹配规则：先判断是否有仓库可以配送所有产品，如果有直接到配送车辆，如果没有随机选择一个仓库，配送尽可能多的产品，
    # 然后再进行判断
    invoice_list = []
    items = [i for i in order.saleinfo_set.all()]
    warehouse_list = Warehouse.objects.all()
    while items is not []:
        for i in warehouse_list:
            if items is []:
                break
            flag = 1
            for j in items:
                storage_list = i.storage_set.filter(p_ID=j.p_id).all()
                number = sum([i.s_number for i in storage_list])
                if number < j.number:
                    flag = 0
                    break
            # 找到了有全部存货的仓库
            if flag:
                ex_warehouse(i, items, order)
                return
        # 这里随机分配
        i = random.choice(warehouse_list)
        ex_warehouse(i, items, order)
        gen_shiptask()


# 采购订单列表
@login_required
def purchase_info(req):
    d = PurchaseOrder.objects.all()
    return render(req, 'purchase_info.html', {'p_order_list': d})


# 采购订单详情
@login_required
def purchase_detail_info(req, id):
    order = PurchaseOrder.objects.filter(number=id).first()
    items = order.purchasedetail_set.all()
    if req.method == "POST":
        if req.POST.get("PAID") == 1:
            order.isPaid = True
            order.isClosed = True
            order.pay_time = datetime.datetime.now()
            order.close_time = datetime.datetime.now()
            order.save()
        else:
            order.isClosed = True
            order.close_time = datetime.datetime.now()
            order.save()
    return render(req, 'purchase_detail_info.html', {'shop_list': items, 'order': order})


# 需求增加
@login_required
def add_demand(req):
    warehouse_id = User.objects.get(id=int(req.session["_auth_user_id"])).u_warehouse_id
    demand_list = Demand.objects.filter(isSolved=False).all()
    return render(req, 'add_demand.html', {'demand': demand_list, 'warehouseID': warehouse_id})


# 需求清单确认
@login_required
def final_demandlist(req, id):
    demand = Demand.objects.filter(number=id).first()
    items = demand.demanddetail_set.all()
    warehouse_id = User.objects.get(id=int(req.session["_auth_user_id"])).u_warehouse_id
    if req.method == "POST":
        count = 1
        for i in items:
            i.quantity = req.POST.get("number" + str(count))
            count = count + 1
            i.save()

    demand.isSolved = True
    demand.save()
    return render(req, 'final_demandlist.html',
                  {'d_demand': items, 'demand': demand, 'demandID': id, 'warehouseID': warehouse_id})


# 生成采购单的时候要按照供应商整合
# 需求单生成采购单
@login_required
def demand2purchase(req, id):
    demand1 = Demand.objects.filter(number=id).first()  # 总demand表
    demand_detail = demand1.demanddetail_set.all()  # demand 细节表
    p_list = [i.product for i in demand_detail]
    sup_list = [supplier.objects.filter(sup_id=p.p_product).first() for p in p_list]
    sup_list = list(set(sup_list))
    if sum([d_d.quantity for d_d in demand_detail]) == 0:
        demand1.isSolved = True
        demand1.save()
        return redirect('/purchase_info')
    # p = demand_detail[0].product
    for sup in sup_list:
        total = 0
        t = datetime.datetime.now()
        number = t.strftime('%H%M%S') + demand1.number[15:] + sup.sup_id

        date = t
        staff = User.objects.get(id=int(req.session["_auth_user_id"]))
        warehouse = demand1.warehouse
        purchse_order = PurchaseOrder.objects.create(number=number, staff=staff, warehouse=warehouse,
                                                     supplier=sup,
                                                     datetime=date, total=total,
                                                     isReceived=False, isPaid=False, isClosed=False)
        for d in demand_detail:
            p = d.product
            if p.p_product == sup.sup_id and d.quantity > 0:
                total += float(d.product.p_price) * float(d.quantity)  # 订单总价
                PurchaseDetail.objects.create(purchase_order=purchse_order, product=p, quantity=d.quantity,
                                              price=d.product.p_price)

        purchse_order.total = total
        purchse_order.save()
    demand1.isSolved = True
    demand1.save()
    return redirect('/purchase_info')

    # p_order_list = PurchaseOrder.objects.all()
    # return render(req, 'purchase_info.html', {'p_order_list': p_order_list})


# 完成运送任务的生成
def gen_shiptask():
    # ccx:生成运送任务与车辆系统对接
    cur = shiptask.objects.all().order_by('-task_id').first()
    task_id = cur.task_id if cur else "0"
    id = int(task_id)
    unpro_invoice = invoice.objects.filter(is_tasked=0).all()
    det = ["包装易碎", "高档牛奶", "特别低温"]
    for u in unpro_invoice:
        id += 1
        cur_task = shiptask(task_id=str(id).zfill(6),
                            invent_loc=u.invent_loc,
                            dest_loc=u.dest_loc,
                            task_time=datetime.today(),
                            task_guide="集装指导方法%d" % (random.randint(1, 10)),
                            task_det=det[random.randint(0, 2)],
                            invoice_id=u.invoice_id,
                            is_schedule=0)
        cur_task.save()
        invoice.objects.filter(invoice_id=u.invoice_id).update(is_tasked=1)
    gen_schedule()


# 完成调度的匹配
def gen_schedule():
    # 调度生成逻辑
    avai_trucks_l = avai_trucks.objects.filter(truck_status="空闲").all()
    cur_schedule_id = schedule.objects.last()
    ship_task_l = shiptask.objects.filter(is_schedule=0).all()
    if ship_task_l:
        num = len(avai_trucks_l)
        if cur_schedule_id:
            id = cur_schedule_id.schedule_id
        else:
            id = "0"
        # 运送任务与可用车辆进行匹配
        if num < len(ship_task_l):
            # 创建一条通知
            create_notification("可用车辆数量不足，已经采用特殊手段",
                                note_type='4',
                                receiver_id=1,
                                url="",
                                creator_id=1)
            ship_task_l = ship_task_l[0:num]
            n_id = int(id)
            for task in ship_task_l:
                n_id += 1
                num = random.randint(0, len(avai_trucks_l) - 1)
                avai_truck = avai_trucks_l[num]
                avai_trucks.objects.filter(truck_id=avai_truck.truck_id).update(truck_status="使用中")
                # TODO:计划使用networkx包进行最短路线规划，目前没有实际数据，不进行规划
                new_schedule = schedule(schedule_id=str(n_id).zfill(4), schedule_route="待真实数据"
                                        , schedule_status="待审核", task_id=task.task_id, truck_id=avai_truck.truck_id)
                shiptask.objects.filter(task_id=task.task_id).update(is_schedule=1)

                new_schedule.save()
                avai_trucks_l = avai_trucks.objects.filter(truck_status="空闲").all()

        else:
            n_id = int(id)
            for task in ship_task_l:
                n_id += 1
                num = random.randint(0, len(avai_trucks_l) - 1)
                avai_truck = avai_trucks_l[num]
                avai_trucks.objects.filter(truck_id=avai_truck.truck_id).update(truck_status="使用中")
                # TODO:计划使用networkx包进行最短路线规划，目前没有实际数据，不进行规划
                new_schedule = schedule(schedule_id=str(n_id).zfill(4), schedule_route="待真实数据"
                                        , schedule_status="待审核", task_id=task.task_id, truck_id=avai_truck.truck_id)
                shiptask.objects.filter(task_id=task.task_id).update(is_schedule=1)
                new_schedule.save()
                avai_trucks_l = avai_trucks.objects.filter(truck_status="空闲").all()


# 奶源控制
def milk_src_view(req):
    item_list = [{'id': '0001', 'name': '沁美农场',
                  'address': '北京市丰台区王佐镇铁匠营村南宫迎宾路与京良路交叉口',
                  'status': '良好',
                  'level': '一级',
                  'quantity': '6000L/天'},
                 {'id': '0001', 'name': '三棵树农场',
                  'address': '北京市顺义区综合路',
                  'status': '良好',
                  'level': '一级',
                  'quantity': '6000L/天'},
                 {'id': '0002', 'name': '留民营生态农场',
                  'address': '北京市大兴区开元街',
                  'status': '良好',
                  'level': '一级',
                  'quantity': '6000L/天'},
                 {'id': '0002', 'name': '富通农场',
                  'address': '北京市通州区前刘路',
                  'status': '一般',
                  'level': '二级',
                  'quantity': '1000L/天'},
                 {'id': '0003', 'name': '南郊和义农场',
                  'address': '北京市丰台区大红门南路',
                  'status': '良好',
                  'level': '一级',
                  'quantity': '4000L/天'},
                 {'id': '0003', 'name': '中兴万佳生态农场',
                  'address': '北京市通州区中兴万佳生态农场(721乡道南)',
                  'status': '一般',
                  'level': '二级',
                  'quantity': '6000L/天'},
                 ]
    return render(req, 'milk_src_view.html', {'item_list': item_list})
